import React, { createContext, useState } from "react"
import classNames from "classnames"
import { MenuItemProps } from "./components/menu_item"

type selectCallback = (selectedIndex: string) => void

export interface MenuProps {
	defaultIndex?: string
	className?: string
	mode?: "vertical" | "horizontal"
	style?: React.CSSProperties
	onSelected?: selectCallback
	defaultOpenedSubMenus?: string[]
}

interface IMenuContext {
	index: string
	onSelected?: selectCallback
	mode?: "vertical" | "horizontal"
	defaultOpenedSubMenus?: string[]
}

export const MenuContext = createContext<IMenuContext>({ index: "0" })

const Menu: React.FC<MenuProps> = props => {
	const { defaultIndex, className, mode, style, onSelected, children, defaultOpenedSubMenus } = props

	const [currentActive, setActive] = useState(defaultIndex)

	const classes = classNames("viking-menu", className, {
		"menu-vertical": mode === "vertical",
		"menu-horizontal": mode !== "vertical",
	})

	const handleClick = (index: string) => {
		setActive(index)
		onSelected && onSelected(index)
	}

	const initialContext: IMenuContext = {
		index: currentActive ? currentActive : "0",
		onSelected: handleClick,
		mode,
		defaultOpenedSubMenus,
	}

	const renderChildren = () => {
		return React.Children.map(children, (child, index) => {
			const childElement = child as React.FunctionComponentElement<MenuItemProps>
			const displayName = childElement.type.displayName
			if (displayName === "MenuItem" || displayName === "SubMenu") {
				return React.cloneElement(childElement, { index: index + "" })
			} else {
				console.warn("Warning: menu has a child which is not MenuItem component!")
			}
		})
	}

	return (
		<ul className={classes} style={style}>
			<MenuContext.Provider value={initialContext}> {renderChildren()}</MenuContext.Provider>
		</ul>
	)
}

Menu.defaultProps = {
	defaultIndex: "0",
	mode: "horizontal",
	defaultOpenedSubMenus: [],
}

export default Menu
